<?php

$start_time = microtime(true);
$workers = [];
$urls = [
    'https://www.baidu.com',
    'https://www.sina.com.cn',
    'https://www.qq.com',
    'https://blog.csdn.net',
    'https://www.swoole.com',
    'https://www.taobao.com',
];

/*
//传统的顺序阻塞处理,需要耗时6s:
foreach ($urls as $url) {
    echo curlData($url);
}
$end_time = microtime(true);
echo "time_cost: " . intval($end_time - $start_time) . " s" . PHP_EOL;
exit;
*/

for ($i = 0; $i < count($urls); $i++) {
    // 子进程,总共只需要 1s
    $process = new swoole_process(function (swoole_process $worker) use ($i, $urls) {
        // curl
        $content = curlData($urls[$i]);
        //echo $content.PHP_EOL;

        $worker->write($content); //把数据写入管道
    }, true);
    $pid = $process->start();
    $workers[$pid] = $process;
}

foreach ($workers as $process) {
    echo $process->read(); //从管道中读取数据
}

$end_time = microtime(true);
echo "time_cost: " . intval($end_time - $start_time) . " s" . PHP_EOL;

/**
 * 模拟请求获取网页的内容,假设每个请求耗时 1s
 * @param $url
 * @return string
 */
function curlData($url) {
    // 模拟 curl 的 file_get_contents() 方法, 这里假设每个curl请求耗时都是1秒
    sleep(1);
    return $url . " --- success" . PHP_EOL;
}
